package in.muton.edushare.poll.panels;

import in.muton.edushare.EduShareSession;
import in.muton.edushare.pages.EduShareBasePage;
import in.muton.edushare.pages.common.EdusharePanel;
import in.muton.edushare.poll.components.DeleteButton;
import in.muton.edushare.poll.questions.NewQuestion;
import in.muton.edushare.schedules.widgets.DateHelper;
import in.muton.edushare.wicket.models.CayenneModel;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.wicket.markup.html.CSSPackageResource;
import org.apache.wicket.markup.html.JavascriptPackageResource;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Button;
import org.apache.wicket.markup.html.form.CheckBox;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.TextArea;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;

import com.edushare.common.constants.ApplicationConstants;
import com.edushare.common.dao.PollsDAO;
import com.edushare.common.util.StringUtil;
import com.edushare.common.vo.Poll;

public class NewPoll extends EdusharePanel {
	private static final long serialVersionUID = 1183361310325142930L;
	IPollPanelContainer container = null;
	private static final Log log = LogFactory.getLog(NewPoll.class);

	public NewPoll(String id, IModel<Poll> model, EduShareBasePage page,
			IPollPanelContainer container, int entityType, int entityId) {
		super(id, model, page);
		this.container = container;
		if (model != null) {
			this.pollModel = model;
			Poll p = model.getObject();
			setPollTitle(p.getPollName());
			setPollDesc(p.getPollDesc());
			setLastDate(new SimpleDateFormat("dd MM yyyy").format(p
					.getPollEndDate()));
			setAnonymous(p.getPollAnonymous() == Poll.ANONYMOUS_POLL ? true
					: false);
			setResultPublic(p.getPollResultsPublic() == Poll.POLL_RESULT_OPEN ? true
					: false);
		}
		init();
	}

	private void init() {
		add(CSSPackageResource
				.getHeaderContribution(PollList.class, "Poll.css"));
		add(JavascriptPackageResource.getHeaderContribution(NewQuestion.class,
				"questions.js"));
		Form<Void> f = new Form<Void>("pollForm");
		add(f);
		setDefaultModel(new CompoundPropertyModel<NewPoll>(this));
		f.add(new TextField<String>("pollTitle"));
		f.add(new TextArea<String>("pollDesc"));
		f.add(new TextField<String>("lastDate"));
		f.add(new CheckBox("anonymous"));
		f.add(new CheckBox("resultPublic"));

		Button b;
		f.add(b = new Button("questionPage") {
			private static final long serialVersionUID = -6400248146198499703L;

			@Override
			public void onSubmit() {
				if (!createPoll())
					return;
				container.setPoll(pollModel);
				container.gotoNextPage();
			}
		});
		b.add(new Label("questionText", new Model<String>() {
			@Override
			public String getObject() {
				if (pollModel != null
						&& pollModel.getObject().getQuestions().size() > 0)
					return "Edit Questions";
				else
					return "Add Questions";
			}

			private static final long serialVersionUID = 8553103923551368583L;
		}));

		f.add(new Button("draft") {
			@Override
			public boolean isVisible() {
				if(pollModel == null)
					return true;
				if (pollModel.getObject().getStatus() == Poll.POLL_STATUS_DRAFT
						&& pollModel.getObject().getCreator() == EduShareSession.get()
								.getLoggedInUser())
					return true;
				return false;
			}
			
			@Override
			public void onSubmit() {
				if (!createPoll())
					return;
				container.setPoll(pollModel);
				if (pollModel != null)
					setError("This poll has been saved as draft. You may return to this poll and edit it anytime.");
			}
			private static final long serialVersionUID = 3304542234185731803L;
		});
		f.add(new DeleteButton("discard", pollModel, container));
	}

	private boolean createPoll() {
		if (!StringUtil.isValid(getPollTitle())) {
			setError("Poll title cannot be empty");
			return false;
		}
		if (StringUtil.isValid(getPollDesc())
				&& getPollDesc().length() > ApplicationConstants.MAX_MSG_SIZE) {
			setError("Please use a shorter poll description.");
			return false;
		}
		try {
			Date lastDate = new SimpleDateFormat("d MMM yyyy")
					.parse(getLastDate());
			Date today = new Date();
			if (DateHelper.before(lastDate, today)) {
				setError("Poll end date must be in the future");
				return false;
			}
		} catch (ParseException e1) {
			e1.printStackTrace();
		}
		if (pollModel != null) {
			Poll p = pollModel.getObject();
			p.setPollName(getPollTitle());
			p.setPollDesc(getPollDesc());
			p.setPollAnonymous(getAnonymous() ? Poll.ANONYMOUS_POLL
					: Poll.NAMED_POLL);
			p.setPollResultsPublic(getResultPublic() ? Poll.POLL_RESULT_OPEN
					: Poll.POLL_RESULT_CLOSED);
			try {
				DateHelper d = new DateHelper(
						new SimpleDateFormat("d MMM yyyy").parse(getLastDate()));
				d.addHours(23).addMins(59);
				p.setPollEndDate(d.getDate());
			} catch (ParseException e) {
				e.printStackTrace();
			}
			new PollsDAO(getORMInterface()).commit();
			return true;
		} else {
			PollsDAO pdao = new PollsDAO(getORMInterface());
			Poll p = pdao.createNewPoll();
			pollModel = new CayenneModel<Poll>(p);
			p.setPollName(getPollTitle());
			p.setCreator(getLoggedInUser());
			p.setStatus(Poll.POLL_STATUS_DRAFT);
			p.setPollDesc(getPollDesc());
			p.setPollAnonymous(getAnonymous() ? Poll.ANONYMOUS_POLL
					: Poll.NAMED_POLL);
			p.setPollResultsPublic(getResultPublic() ? Poll.POLL_RESULT_OPEN
					: Poll.POLL_RESULT_CLOSED);
			try {
				DateHelper d = new DateHelper(
						new SimpleDateFormat("d MMM yyyy").parse(getLastDate()));
				d.addHours(23).addMins(59);
				p.setPollEndDate(d.getDate());
			} catch (ParseException e) {
				e.printStackTrace();
			}
			new PollsDAO(getORMInterface()).commit();
			return true;
		}
	}

	private String pollTitle = "";
	private String pollDesc = "";
	private String lastDate = "";
	private Boolean resultPublic = false;
	private Boolean anonymous = false;

	private IModel<Poll> pollModel = null;

	public String getPollDesc() {
		return pollDesc;
	}

	public void setPollDesc(String pollDesc) {
		this.pollDesc = pollDesc;
	}

	public String getLastDate() {
		return lastDate;
	}

	public void setLastDate(String lastDate) {
		this.lastDate = lastDate;
	}

	public Boolean getResultPublic() {
		return resultPublic;
	}

	public void setResultPublic(Boolean resultPublic) {
		this.resultPublic = resultPublic;
	}

	public Boolean getAnonymous() {
		return anonymous;
	}

	public void setAnonymous(Boolean anonymous) {
		this.anonymous = anonymous;
	}

	public void setPollTitle(String pollTitle) {
		this.pollTitle = pollTitle;
	}

	public String getPollTitle() {
		return pollTitle;
	}
}
